#!/usr/bin/env python3
# _*_ coding:utf-8 _*_


from django.shortcuts import redirect, render, HttpResponse
from rbac import models
from django.contrib.auth.hashers import check_password, make_password
from rbac.init.permission import init_permission


def login(request):
    if request.method == 'GET':
        return render(request, 'rbac/login.html')

    username = request.POST['username']
    passwd = request.POST['passwd']
    user_obj = models.User.objects.filter(username=username).first()
    if user_obj:
        if check_password(passwd, user_obj.passwd):
            request.session['ID'] = user_obj.pk
            init_permission(user_obj, request)
            return redirect('index')
        else:
            return render(request, 'rbac/login.html', {'error': '账号密码错误！'})
    else:
        return render(request, 'rbac/login.html', {'error': '账号不存在！！！'})


def logout(request):
    request.session.delete()
    return redirect('rbac:login')


def resetpasswd(request, pk):
    if request.method == 'POST':
        if pk == request.POST.get('pk') and request.POST.get('csrfmiddlewaretoken'):
            user_obj = models.User.objects.filter(id=pk).first()
            passwd = make_password('fy123123')
            user_obj.passwd = passwd
            user_obj.save()
            return HttpResponse('200')

    return render(request, '404.html', {'error': '账号不存在！！！'})
